//
//  PlayMusicViewController.m
//  Auditory
//
//  Created by 寒竹子 on 15/5/5.
//  Copyright (c) 2015年 寒竹子. All rights reserved.
//  音乐播放页面

#import "PlayMusicViewController.h"
#import "FSPlaylistItem.h"
#import "songListModel.h"
#import "Globle.h"
#import "XRRadioView.h"
#import "MusicModel.h"
#import <MediaPlayer/MediaPlayer.h>

@interface PlayMusicViewController ()<XRRadioViewDelegate>

@property (nonatomic, strong) XRRadioView * radioView;
@property (nonatomic, strong) MusicModel * songModel; // 歌曲信息

@end

@implementation PlayMusicViewController

- (instancetype)init
{
    if (self = [super init]) {
        // 收到进入后台通知  设置歌曲信息
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackgroundSetSongInfo:) name:XRRadioViewSetSongInfoNotifiCation object:nil];
        
        [self setupUI];
    }
    
    return self;
}

/**
 * @brief  单例
 *
 * @param
 * @return
 */
+ (instancetype)sharedPlayController
{
    static PlayMusicViewController * playVc = nil;
    dispatch_once_t once = 0l;
    dispatch_once(&once, ^{
        if (playVc == nil) {
            playVc = [[self alloc] init];
        }
    });
    
    return playVc;
}

// 返回
- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 * @brief  初始化UI
 *
 * @param
 * @return
 */
- (void)setupUI
{
    self.view.backgroundColor = RGB(250, 250, 250, 1.0f);
    
    typeof(self) weakSelf = self;
    
    _radioView = [[XRRadioView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    _radioView.callBlock = ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    
    _radioView.delegate = self;
    [self.view addSubview:_radioView];
}

/**
 * @brief  播放音乐
 *
 * @param
 * @return
 */
- (void)playMusicWithSongLink:(songListModel *)model
{
    
#if 0
    // 本地音乐
    FSPlaylistItem * item = [[FSPlaylistItem alloc] init];
    item.title = _songModel.title;
    
    NSString * documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString * myMusicFiles = [documentPath stringByAppendingPathComponent:@"myMusicFiles"];
    
    NSString * filePath = [myMusicFiles stringByAppendingPathComponent:@"1.mp3"];
    item.url = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@", filePath]];
    NSLog(@"url: %@", item.url);
    
    _radioView.model = _songModel; // 传入歌曲信息model
    
    self.globle.isPlaying = YES;
    _radioView.seletedPlayItem = item;
    
    // 如果程序进入后台
    if (self.globle.isApplicationEnterBackground) {
        [self applicationEnterBackgroundSetSongInfo:nil];
    }
    
#else
    
    NSString * baseURL = SongURL;
    // 拼接后缀
    baseURL = [baseURL stringByAppendingFormat:@"%@/info?", model.songId];
    
    // 拼接参数
    NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
    [params setValue:@"85b8336a-607f-33ed-b27d-7622f2dcffa3" forKey:@"uuid"];
    
    [Network getJSONWithBaseURL:baseURL params:params returnCall:^(id JSON, NSError *error) {
        if (!error) {
            NSDictionary * dict = (NSDictionary *)JSON;
            
            _songModel = [[MusicModel alloc] init];
            [_songModel setValuesForKeysWithDictionary:dict];
            
            NSDictionary * subDict = dict[@"owner"];
            _songModel.iconURL = subDict[@"icon"];
            _songModel.nickName = subDict[@"nickname"];
            
            FSPlaylistItem * item = [[FSPlaylistItem alloc] init];
            item.title = _songModel.title;
            item.url = [NSURL URLWithString:_songModel.songURL];
            _radioView.model = _songModel; // 传入歌曲信息model
            
            self.globle.isPlaying = YES;
            self.globle.playingIndex = self.index;
            /*
             判断是否有可供播放的音频资源
             */
            if (_dataArray.count > 0) {
                self.globle.isHasResource = YES;
            }else {
                self.globle.isHasResource = NO;
            }
            _radioView.seletedPlayItem = item;
            
            // 如果程序进入后台
            if (self.globle.isApplicationEnterBackground) {
                [self applicationEnterBackgroundSetSongInfo:nil];
            }
        }else {
            // 歌曲信息获取失败
            [self playMusicLock];
            
            NSLog(@"网络错误");
        }
    }];
    
#endif
}

/**
 * @brief  应用程序进入后台处理
 *
 * @param
 * @return
 */
- (void)applicationEnterBackgroundSetSongInfo:(NSNotification *)nf
{
    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
        NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
        [dict setObject:_songModel.title forKey:MPMediaItemPropertyTitle];
        [dict setObject:_songModel.duration forKey:MPMediaItemPropertyPlaybackDuration];
//        UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_songModel.iconURL]] scale:1.0f];
        UIImage * image = [UIImage imageNamed:@"headDefault"];
        [dict setObject:[[MPMediaItemArtwork alloc] initWithImage:image] forKey:MPMediaItemPropertyArtwork];
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    }
}

/**
 * @brief  单曲循环播放
 *
 * @param
 * @return
 */
- (void)playMusicLock
{
    FSPlaylistItem * item = [[FSPlaylistItem alloc] init];
    item.title = _songModel.title;
    item.url = [NSURL URLWithString:_songModel.songURL];
    _radioView.seletedPlayItem = item;
    _radioView.model = _songModel;
    self.globle.isPlaying = YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 隐藏导航
    self.navigationController.navigationBarHidden = YES;
    // 隐藏AudioToolBar
    [[NSNotificationCenter defaultCenter] postNotificationName:KHiddenAudioToolBarNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    // 显示导航
    self.navigationController.navigationBarHidden = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:KShowAudioToolBarNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - XRRadioViewDelegate

// 顺序 随机 单曲
- (void)radioView:(XRRadioView *)view musicStop:(NSInteger)playType
{
    songListModel * model = nil;
    
    switch (playType) {
        case 0:
        {
            // 顺序播放
            self.index += 1;
            if (self.index >= [self.dataArray count]) {
                self.index = 0;
            }
            model = [self.dataArray objectAtIndex:self.index];
            
            [self playMusicWithSongLink:model];
        }
            break;
        case 1:
        {
            // 随机播放
            NSInteger num = [self.dataArray count];
            model = [self.dataArray objectAtIndex:arc4random() % num];
            
            [self playMusicWithSongLink:model];
        }
            break;
        case 2:
        {
            // 单曲播放
            model = self.model;
            [self playMusicLock];
        }
            break;
        default:
            break;
    }
}

/**
 * @brief  上一首
 *
 * @param
 *
 * @return
 */
- (void)radioView:(XRRadioView *)view preSwitchMusic:(UIButton *)preButton
{
    if (self.dataArray.count != 0) {
        self.index -= 1;
        if (self.index < 0) {
            self.index = 0;
        }
        
        songListModel * model = [self.dataArray objectAtIndex:self.index];
        self.globle.playingIndex = self.index;
        [self playMusicWithSongLink:model];
    }
}

/**
 * @brief  下一首
 *
 * @param
 *
 * @return
 */
- (void)radioView:(XRRadioView *)view nextSwitchMusic:(UIButton *)nextButton
{
    if ([self.dataArray count] != 0) {
        self.index += 1;
        if (self.index >= [self.dataArray count]) {
            self.index -= 1;
        }
        songListModel * model = [self.dataArray objectAtIndex:self.index];
        self.globle.playingIndex = self.index;
        [self playMusicWithSongLink:model];
    }
}

/**
 * @brief  评论
 *
 * @param
 *
 * @return
 */
- (void)radioViewCommentAction
{
    NSLog(@"评论");
}

/**
 * @brief  收藏
 *
 * @param
 *
 * @return
 */
- (void)radioViewLikeAction
{
    NSLog(@"收藏");
}

/**
 * @brief  分享
 *
 * @param
 *
 * @return
 */
- (void)radioViewShareAction
{
    NSLog(@"分享");
}

/**
 * @brief  列表
 *
 * @param
 *
 * @return
 */
- (void)radioViewListAction
{
    NSLog(@"列表");
}

@end
